package com.ruoyi.system.mongo.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.mongodb.AllSchool;
import com.ruoyi.system.domain.mongodb.Schools;
import com.ruoyi.system.domain.mongodb.Teacher;
import com.ruoyi.system.mongo.TeacherDao;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author yangtao
 * @since 2021-03-02 17:01
 */
@Component
public class TeacherDaoImpl implements TeacherDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public PageInfo<Teacher> teacherList(String realname,String phoneNum, String schoolId,Integer pageNum,Integer pageSize) {
        Pattern pattern=Pattern.compile("^.*"+realname+".*$", Pattern.CASE_INSENSITIVE);
        if(pageNum != 0){
            pageNum = pageNum/pageSize;
        }
        Sort sort = Sort.by(Sort.Direction.ASC, "time");
        Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
        Query query;
        if (realname.trim().length()==0&&phoneNum.trim().length()==0){
            query = new Query(Criteria.where("role").is(9));
        }else if (realname.trim().length()!=0&&phoneNum.trim().length()==0){
            query = new Query(Criteria.where("role").is(9).and("realname").regex(pattern));
        }else if (realname.trim().length()==0&&phoneNum.trim().length()!=0){
            query = new Query(Criteria.where("role").is(9).and("phoneNum").is(phoneNum));
        }else {
            query = new Query(Criteria.where("role").is(9).and("phoneNum").is(phoneNum). and("realname").regex(pattern));
        }
        if (!StringUtils.isEmpty(schoolId)) {
            query.addCriteria(Criteria.where("school").is(new ObjectId(schoolId)));
        }
        PageHelper.startPage(pageNum,pageSize);
        long total = mongoTemplate.count(query, Teacher.class,"users");
        List<Teacher> teachers = mongoTemplate.find(query.with(pageable), Teacher.class,"users");

        PageInfo<Teacher> pageInfo = new PageInfo<>();
        pageInfo.setList(teachers); //结果集
        pageInfo.setTotal(total);  //总条数
        return pageInfo;
    }
}
